package l1j.server.server.command.executor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.utils.SQLUtil;
import l1j.server.server.Account;

public class L1CleanOnline implements L1CommandExecutor{
	private L1CleanOnline() {
	}

	public static L1CommandExecutor getInstance() {
		return new L1CleanOnline();
	}

	@Override
	public void execute(L1PcInstance pc, String cmdName, String arg) {
		try {
			Account account = Account.load(arg);
			boolean online = account.isOnlined();
			boolean onlines = account.isOnlineStatus();
			if (account != null) {
				if (onlines && !online){
					Account.OnlineStatus(account, false);
					loadchar(arg);
					pc.sendPackets(new S_SystemMessage("該帳號卡登狀態已被清除。"));
				} else {
					pc.sendPackets(new S_SystemMessage("此玩家狀態不能被清除，請提示玩家到問題回報區留言。"));
				}
			}
		}
		catch (Exception e) {
			pc.sendPackets(new S_SystemMessage("請輸入 : " + cmdName + " 玩家名稱。"));
		}
	}
	
	private void loadchar(String account_name) {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("SELECT char_name FROM characters Where account_name=?");
			pstm.setString(1, account_name);
			rs = pstm.executeQuery();			
			while (rs.next()){
				updatecharonline(rs.getString("char_name"));
			}			
		}
		catch (SQLException e) {
		}
		finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
	private void updatecharonline(String charname){
		Connection con = null;
		PreparedStatement pstm = null;
		try{
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("UPDATE characters SET OnlineStatus=0 WHERE char_name =?");
			pstm.setString(1, charname);
			pstm.execute();
		} catch  (SQLException e){
			
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
}
